package com.zjk.gateway.filter;

import com.zjk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @author: gfk
 * @create: 2022/10/31
 * @Description:
 * @FileName: UserFilter
 * @History:
 * @自定义内容：
 */
@Component
public class UserFilter implements GlobalFilter, Ordered {

    @Autowired
    RedisTemplate redisTemplate;

    private String[] whiteArray = new String[]{
            "login","uploadOss","uploadFastDFS"
    };
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();//干什么

        //白名单放行
        for(String white:whiteArray){
            if(path.contains(white)){
                return chain.filter(exchange);//放行
            }
        }
        //请出示证件
        String authorization = request.getHeaders().getFirst("Authorization");
        if(StringUtils.isEmpty(authorization)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);////没有拿证件，回去吧
            return response.setComplete();
        }
        String token = authorization.replace("Bearer ", "");
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);////没有拿证件 回去吧
            return response.setComplete();
        }
        try {
            Claims jwt_body = JwtUtils.getJwt_Body(token);
            String userid = (String)jwt_body.get("userid");
            String username = (String)jwt_body.get("username");
            String token_redis = (String)redisTemplate.opsForValue().get("token:" + userid);
            if(StringUtils.isEmpty(token_redis)){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);////不合法，超期，伪造 回去吧
                return response.setComplete();
            }
            redisTemplate.expire("token:" + userid,2, TimeUnit.MINUTES);//续期
            return chain.filter(exchange);//放行

        }catch (Exception e){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);////不合法，超期，伪造 回去吧
            return chain.filter(exchange);//放行
        }
    }

    @Override
    public int getOrder() {
        return -100;
    }
}